<?php

namespace app\api\controller;

use app\admin\model\information\InventoryClass;
use app\admin\model\information\Shelves;
use app\admin\model\inventory\Kc;
use app\admin\model\information\Actionlog;
use app\common\controller\Api;
//use app\common\library\Log;
use think\Log;
use think\Config;
use think\Db;
use think\Exception;
use fast\Tree;
use addons\crontab\controller\Pda;
use app\common\model\Temporary;
use app\admin\model\inventory\Wmskc;
use app\common\model\Inventory;
use think\db\Query;
use app\common\model\InvShelvesLatest;

use app\admin\model\outhouse\CheckVouchList;
use app\admin\model\outhouse\CheckVouch;
use app\admin\model\information\U8department;
use app\admin\model\information\Oaflowrun;
use think\Request;

/**
 * 仓库基础资料
 */
class Wms extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $pc_type_arr = [
        0 => 1, //收货对应pctype的1
        1 => 5,  //上架对应pctype的5（原货架（可能是库区），现货架）源单上架
        3 => 2,  //领料出库对应pctype的2
        4 => 14, //产品入库 ---new
        5 => 15, //销售出库 ---new
        11 => 3,  //其他入库
        12 => 4,  //其他出库
        13 => 9, //盘点
        14 => 6, //采购退回
        15 => 7, //领料退回
        16 => 8, //调拨
        17 => 10, //直接上架
        18 => 11, //直接领料
        2  => 12,  //拣货单-》拣货出库
        19 => 16  //组装单
    ];
    protected $pda_typeflag_arr = [
        1 => 'SIN', //收货对应pctype的1
        12  => 'PK',  //拣货单-》拣货出库
        5 => 'IN',  //上架对应pctype的5（原货架（可能是库区），现货架）源单上架
        2 => 'OUT',  //领料出库对应pctype的2
        3 => 'OIN',  //其他入库
        4 => 'OOUT',  //其他出库
        //13 => 9, //盘点
        6 => 'QASN', //采购退回
        7 => 'QOUT', //领料退回
        8 => 'DB', //调拨
        10 => 'IN', //直接上架
        11 => 'OUT', //直接领料
        14 => 'PIN',//产品入库
        15 => 'SEOUT',//销售出库
        16 => 'ZZ' //组装单
    ];

    /**
     * 获取仓库列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWarehouseList(){
        $data = \app\common\model\Warehouse::getList();
        //保存文件
        save_json_by_type('warehouse',$data);
        $this->success('成功',$data);
    }

    /**
     * 获取货架列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getShelvesList(){
        $data = \app\common\model\Shelves::getList();
        //保存文件
        save_json_by_type('shelves',$data);
        $this->success('成功',$data);
    }
    /**
     * 获取货架分类限制
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getShelvesInvclass($type = 1){
        $data = db('shelves_invclass')->alias('a')
        ->field('a.*,(select b.cInvCCode from fa_inventory_class b where b.id=a.inv_class_id) classification_id')
        ->select();
       
        //保存文件
        save_json_by_type('shelvesInvclass',$data);
        if($type == 1){
            $this->success('成功',$data);
        }
    }

    /**
     * 获取采购入库
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getProcureList($flag='',$dataPath=''){
        $data = \app\common\model\Procure::getList();
        //save_json_by_type('procure',$data);
        //保存文件
        if(!$dataPath){
            $dataPath = Config::get('path_json_data');
        }
        //uploads/data file_put_contents($dataPath . 'procure.json', json_encode($data, true));
        file_put_contents(ROOT_PATH . '/public/'.$dataPath.'procure.json', json_encode($data, true));
        
        if(!$flag == 'add'){
            $this->success('成功',$data);
        }
    }
    /**
     * 获取物料档案表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInventoryList($type = 1){
        //$allData     = \app\common\model\Inventory::getList();
        $allData = [];
        $count    = db('inventory')
        ->where([
            'deletetime' => null,
            'classification_id' => ['not like','0810%']
        ])
        ->where([
            'classification_id' => [['like','06%'],['like','08%'], 'or']
        ])
        ->count();
        $pageSize = 6000;
        $pageList  = ceil($count/$pageSize);
        
        $dataPath = Config::get('path_json_data');
        if (!is_dir($dataPath)) {
            mkdir($dataPath, 0777, true);
        }
        $field = 'id,ifnull(warehouse_id,0) warehouse_id,ifnull(shelves_id,0) shelves_id,ifnull(shelves_name,"") shelves_name,number,name,ifnull(specification,"") specification,attributes,
        classification_name,classification_id,unit,unit_code,mbatch,ifnull(safe_num,"") safe_num,ifnull(max_num,"") max_num,
        ifnull(min_num,"") min_num,ifshangjia,ifjianhuo';
        
        //删掉旧数据
        $x = 1;
        while (file_exists($dataPath . 'inventory'.$x.'.json')) {
            unlink($dataPath . 'inventory'.$x.'.json');
            $x++;
        }
        
        for ($i = 0; $i < $pageList; $i++) {
            $y  = $i+1;
            $data = db('inventory')->field($field)->page($y, $pageSize)->where([
                'deletetime' => null,
                'classification_id' => ['not like','0810%']
            ])
            ->where([
                'classification_id' => [['like','06%'],['like','08%'], 'or']
            ])
            ->select();
            $saveData = json_encode($data, true);
            file_put_contents($dataPath . 'inventory'.$y.'.json', $saveData);
            $allData = array_merge($allData,$data);
        }
        
        if($type == 1){
            $this->success('成功',$allData);
        }else{
            return $allData;
        }
    }

    /**
     * 获取物料库存列表
     * @return void
     */
    public function getKcList($flag = '',$dataPath=''){
        /* $data = \app\common\model\Kc::getList();
        //保存文件
        save_json_by_type('kc',$data);
        if($flag == 'add'){
            Log::write('pda点同步按钮同时，更新库存文件');
        }else{
            $this->success('成功',$data);
        } */
        
        $field = 'id,warehouse_id,warehouse_number,warehouse_name,
inv_id,inv_name,inv_number,IFNULL(inv_specification,"") inv_specification,
inv_unit,inv_unit_code,
shelves_id,shelves_name,shelves_number,shelves_type,
quantity,cur_quantity,classification_id,classification_name';
        $data = collection(Wmskc::field($field)->where([
            'status' => 1,
            'quantity' => ['GT',0]
        ])->select())->toArray();
        
        //保存文件
        //save_json_by_type('kc',$data);
        if(!$dataPath){
            $dataPath = Config::get('path_json_data');
        }
        file_put_contents($dataPath . 'kc.json', json_encode($data, true));
        
        if($flag == 'add'){
            Log::write('pda点同步按钮同时，更新库存文件');
        }else{
            $this->success('成功',$data);
        }
    }
    
    /**
     * 获取库存明细
     * @return void
     */
    public function getKcmxList(){
        $data = \app\common\model\kcmx::getList();
        //保存文件
        save_json_by_type('kcmx',$data);
        $this->success('成功',$data);
    }

    /**
     * 获取领料列表
     * @return void
     */
    public function getMaterialList($flag='',$dataPath=''){
        $data = \app\common\model\Material::getList();
        //save_json_by_type('procure',$data);
        //保存文件
        if(!$dataPath){
            $dataPath = Config::get('path_json_data');
        }
        //uploads/data
        file_put_contents(ROOT_PATH . '/public/'.$dataPath.'appmaterial.json', json_encode($data, true));
        if(!$flag == 'add'){
            $this->success('成功',$data);
        }
    }

    public function getUsers($type = 1){
        //读u8用户
        //$data = Db::connect('database.sec')->table('UA_User_Ex')->field('cUser_Id userid,cUser_Name username')->select();
        
        //读wms平台管理员
        $data = db('admin')
        ->field('CONCAT("wms","_",id) userid,username,nickname')
        ->where([
            'status' => 'normal',
            'username' => ['NEQ','admin']
        ])
        ->select();
        
        save_json_by_type('user',$data);
        if($type == 1){
            $this->success('成功',$data);
        }
    }
    
   /*
    * 物料分类
    *   */
    public function getInventoryClassList($type = 1){
        $data = InventoryClass::geTreeData();
        $tree = InventoryClass::listToTreeByRecursion($data);
        save_json_by_type('inventory_class',$tree);
        if($type == 1){
            $this->success('成功',$tree);
        }
    }
    
    /*
     * 货架、库区 树
     *   */
    public function getShelvesTree($type = 1){
        $shelves = new Shelves();
        $tree = $shelves->getTreeData();
        $tree = InventoryClass::listToTreeByRecursion($tree);
        save_json_by_type('shelves_tree',$tree);
        if($type == 1){
            $this->success('成功',$tree);
        }
    }
    /**
     * @return void
     */
    public function getDataSummary(){
        $data = \app\common\model\Warehouse::getList();
        save_json_by_type('warehouse',$data);
        
        $data = \app\common\model\Shelves::getList();
        save_json_by_type('shelves',$data);
        
        //放在采购订单里同步
        //$data = \app\common\model\Procure::getList();
        //save_json_by_type('procure',$data);
        
        $this->getInventoryList(2);
        
        //库存
        $this->getKcList('add');

        //$data = \app\common\model\Material::getList();
        //save_json_by_type('material',$data);
        
        $this->getUsers(2);
       
        $this->getInventoryClassList(2);
        $this->getShelvesTree(2);
        $this->getShelvesInvclass(2);
        
        //记录同步时间
        save_json_file('syn_datetime.json',['datetime'=>date('Y-m-d H:i:s',time())]);
        
        //生成物料和货架的最新关联信息
        $invShData = InvShelvesLatest::addData();
        save_json_by_type('invShelvesLastest',$invShData);
        
        $this->getCheckvouchList();
        
        $this->success();
    }

    /**
     * 添加临时数据
     * @return void
     */
    public function createTemporaryData()
    {
        $data = file_get_contents("php://input");
        if(empty($data) ){
           $this->error();
        }
        $data = json_decode($data,true);
        Db::name('temporary')->insertAll($data);
        $this->success();
    }

    /**
     * 创建临时领料表
     * @return void
     */
    public function createTemporaryMaterial(){
        $oaData = $this->request->post();
        $data = [];
        
        //组装数据
        if(empty($oaData)||empty($oaData['DATA_10']['id'])){
            \think\Log::error('temporary_material :没数据提交 时间：'.date('Y-m-d H:i:s'));
            //abort('500','没数据提交');
            exit();
        }
        try
        {
            foreach ($oaData['DATA_10']['id'] as $k=>$v){
                $inventory_number = $oaData['DATA_10']['DATA_10_6'][$k];
                if(isset($oaData['DATA_10']['DATA_10_8'][$k])&&$oaData['DATA_10']['DATA_10_8'][$k]=='BG'){
                    //物料分类BG的不同步
                    continue;
                }
                if(substr($inventory_number, 0,2)!='08'&&substr($inventory_number, 0,2)!='04'){
                    //只取五金和固定资产
                    continue;
                }
                if(substr($inventory_number, 0,4)=='0810'){
                    //化学类的，过滤掉
                    continue;
                }
                
                //项目名，当部门名称
                $u8_dpt_code ='';
                if(!empty($oaData['DATA_34'])){
                    $u8_dpt_code = U8department::where('cDepName',$oaData['DATA_34'])->value('cDepCode');
                }
                
                //查询oa流程表，获得oa流水号
                $oa_order_code = Oaflowrun::where('run_id',$oaData['run_id'])->value('run_seq_strip_tags');
                
                $data = [
                    'auto_id'=>$oaData['id'],
                    'material_code'=>$oa_order_code,//$oaData['DATA_1'],//领料单编号
                    'order_date'=>$oaData['DATA_27'],//仓里放行日期
                    'inventory_number'=>$inventory_number,//物料编号
                    'inventory_class'=>$oaData['DATA_10']['DATA_10_6'][$k],//物料分类
                    'quantity'=>$oaData['DATA_10']['DATA_10_3'][$k],//数量
                    'remark'=>$oaData['DATA_10']['DATA_10_4'][$k],
                    'oa_data'=>json_encode($oaData),
                    'applytime'=>$oaData['DATA_12'],
                    'applyer'=>$oaData['DATA_2'],
                    'receiver'=>$oaData['DATA_5'],
                    'receivertime'=>$oaData['DATA_27'],
                    'fitemssname'=>$oaData['DATA_34'],//项目名，当部门名称
                    'fitemss'=>$oaData['DATA_16_TEXT'],
                    'createtime'=>date('Y-m-d H:i:s'),
                    'updatetime'=>date('Y-m-d H:i:s')
                ];
                Db::name('temporary_material')->insert($data);
                
                //添加领料单 表头
                if(!db('material')->where(['material_code'=>$data['material_code']])->find()){
                    $materialData = [
                        'material_code'=>$data['material_code'],
                        'order_date'=>$data['order_date'],
                        'crdname' => '生产领用',
                        'crdcode' => '22',
                        //'sh_time'=>'',
                        'status'=>1,
                        'source'=>1,
                        'fitemss'=>$data['fitemss'],
                        'fitemssname'=>$oaData['DATA_34'],
                        'createtime'=>$oaData['DATA_19'],
                        'fitemsbs' => $oaData['DATA_33_TEXT'],
                        //'cUser_Id' => $oaData['userInfo']['user_accounts'],
                        //'cUser_Name' => $oaData['userInfo']['user_name'],
                        'cUser_Id' => $oaData['DATA_5'],
                        'cUser_Name' => $oaData['DATA_5_TEXT'],
                        'cdepname' => $oaData['DATA_3'],
                        'cdepcode' => $u8_dpt_code
                    ];
                    Db::name('material')->insert($materialData);
                }
                
                $materialListData = [
                    'auto_id' => '',
                    'material_code' => $data['material_code'],
                    'row_id' => $k+1,
                    'inv_id' => db('inventory')->where(['number'=>$inventory_number])->value('id'),
                    'inventory_number' => $inventory_number,
                    'quantity' => $data['quantity'],
                    'createtime'=>date('Y-m-d H:i:s'),
                    'remark' => $data['remark']
                ];
                
                //获得推荐路径，在物料里
                $wh_sh_arr = Inventory::getTjWhShByInvNumber($inventory_number);
                if($wh_sh_arr){
                    $materialListData['warehouse_id'] = $wh_sh_arr['warehouse_id'];
                    $materialListData['tj_shelves_id'] = $wh_sh_arr['shelves_id'];//推荐货架id，查询最新库存记录
                }
                
                Db::name('material_list')->insert($materialListData);
             }
        }catch (Exception $e){
            \think\Log::error('temporary_material :'.$e->getMessage().' 时间：'.date('Y-m-d H:i:s'));
            myLog('外发领料申请异常',$e->getMessage().' 时间：'.date('Y-m-d H:i:s'));
            //abort('500',$e->getMessage());
        }
        exit();
    }
    
    public function checkTemporaryMaterialData(){
        $oaData = $this->request->post();
        if(empty($oaData)||!isset($oaData['DATA_10'])){
            echo '请选择领料物资';
            exit();
        }
        if(empty($oaData['DATA_10'])){
            echo '请选择领料物资';
            exit();
        }
        foreach ($oaData['DATA_10'] as $kk=>$vv ){
//            if(empty($vv['DATA_10_7'][0]))
            if(empty($vv['DATA_10_3'])){
                echo '请填写领取数量';
                exit();
            }
        }
        echo 1;
    }
    
    /**
     * 获取盘点任务
     * @return void
     * @throws \think\exception\DbException
     */
    public function getCheckvouchList(){
        $main = collection(CheckVouch::where('status',1)
            ->field('id,code,code_date,book_date,warehouse_id,type,inv_number_start,inv_number_end,ifnull(shelves_des,"") shelves_des,ifnull(inv_class_name,"") inv_class_name,pda,remark')
            ->select())->toArray();
        $detail = [];
        if($main){
            foreach ($main as $m){
                $rows = collection(CheckVouchList::where([
                    'code'=>$m['code'],
                    //'scan_flag'=>0 //未扫描的
                    ])
                    ->field('id,inv_id,cInvCode inv_number,code,iQuantity kc_qty,iCVCQuantity check_qty,shelves_id,isnew,shelves_name,scan_flag,ifnull(scantime,"") scantime')
                    ->select())->toArray();
                
                $detail[$m['code']] = $rows;
            }
        }
        
        $data = [
            'main'=>$main,
            'detail'=>$detail
        ];
        
        //保存文件
        save_json_by_type('checkVouch',$data);
        //$this->success('成功',$data);
        echo 'checkVouch ok';
    }

    //获取mysql定时任务生成的json文件
    public function getjson(){
        $filename = $_REQUEST['filename'];
        $filename = 'uploads/data/'.$filename.'.json';
        
        if($_REQUEST['filename'] == 'inventory'){
            $filename_arr = [];
            //循环10次
            for($i=1;$i<=10;$i++){
                $new_file_name = str_replace('inventory', "inventory{$i}", $filename);
                if(file_exists($new_file_name)){
                    $filename_arr[] = $new_file_name;
                }else{
                    break;
                }
            }
            if(!empty($filename_arr)){
                $this->success('',$filename_arr);
            }else{
                $this->error('服务器：不存在'.$_REQUEST['filename'].'文件');
            }
        }else{
            if (file_exists($filename)){
                $this->success('',$filename);
            }else{
                $this->error('服务器：不存在'.$_REQUEST['filename'].'文件');
            }
        }
    }
    
    //判断pc端是否存在未处理单据$flag=false远程请求，$flag=true本地调用 
    //$order_type_arr 指定单据类型
    public function getPcBillStatus($flag = false,$order_type_arr = []){
        //判断是否有未处理单据，有则提示
        $order_type_str = $this->request->post('order_type_str','');
        $where = [
          'status' => 0,
          'order_list' => ['NEQ',9] //有盘点单未处理的也能传，因为盘点单是最后才处理的（有做限制）
        ];
        
        if($order_type_str){
            $order_type_arr = explode(',', $order_type_str);
        }
        
        if($order_type_arr){
            $where['order_list'] = ['IN',$order_type_arr];
        }
        
        $check_no_deal = Temporary::where($where)->find();
        if($check_no_deal){
            if($flag){
                exception('后台存在未处理单据，请先处理');
            }else{
                $this->error('后台存在未处理单据，请先处理');
            }
        }
    }
    
    /*
     * 获取app版本号
     *   */
    public function getAppVersion(){
        $data = [
            'version' => config('site.app_version'),
            'apk' => config('site.app_url')//config('site.apk_host').
        ];
        $this->success('ok',$data);
    }
    
    /* 
     * PDA获得最大单号
     *  */
    public function getTodayMaxCode(){
        $today = date('Y-m-d',time());
        $uuid = $this->request->get('uuid','');
        
        //pda单据型号
        $pda_flag = getPdaFlag($uuid);
        if(!$pda_flag){
            //exception('请先设置对应PDA标识');
            $this->error('请先在WMS平台绑定PDA设备');
        }
        
        //最大单号
        $max_rows = Db::query("SELECT cast(MAX(RIGHT(order_code,3)) as UNSIGNED) max_num, order_list
            FROM fa_temporary
            WHERE DATE(createtime) = '{$today}' AND SUBSTRING(order_code,1,2)='{$pda_flag}' AND order_list!=9
            GROUP BY order_list");
        if($max_rows){
            foreach ($max_rows as &$max_row){
                if(isset($this->pda_typeflag_arr[$max_row['order_list']])){
                    $max_row['pre_str'] = $this->pda_typeflag_arr[$max_row['order_list']];
                }
            }
        }
        $this->success('ok',$max_rows);
    }
    
    /*
     * 撤销pda同步状态，判断是否pc端处理结果为失败
     *   */
    public function unSyn(){
        $order_code = $this->request->get('order_code','');
        $uuid = $this->request->get('uuid','');
        try{
            if(!$order_code){
                exception('order_code参数不能为空');
            }
            
            $pda_flag = getPdaFlag($uuid);//设备类型数组
            if(!$pda_flag){
                exception('请先设置对应PDA标识');
            }
            
            $temp = db('temporary')->where('order_code',$pda_flag.$order_code)->find();
            if($temp){
                //exception('不存在单号'.$pda_flag.$order_code);
                if($temp['status']==0){
                    exception('该单据等待处理，无法撤销');
                }
                if($temp['status']==1){
                    exception('该单据已被处理，无法撤销');
                }
            }
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success();
    }
    
    /*
     * 获取对应pda的拣货单，防止pda清空数据
     *   */
    public function synPdaorder(){
        $uuid = $this->request->post('uuid','');
        //$status = $this->request->post('status',1);//pda单据状态，默认1
        $pda_order_type = $this->request->post('order_type','');//pda单据类型
        
        if(!$pda_order_type){
            exception('PDA单据类型为空');
        }
        
        $order_list = $this->pc_type_arr[$pda_order_type];
        $pda_typeflag = $this->pda_typeflag_arr[$order_list];//单据前缀
        
        try{
            $pda_flag = getPdaFlag($uuid);//设备类型数组
            
            if(!$pda_flag){
                exception('请先设置对应PDA标识');
            }
            
            $temps = db('temporary')->alias('t')->where([
                'order_code' => ['like',"{$pda_flag}{$pda_typeflag}%"],
                'order_list' => $order_list,
                'status' => ['IN',[0,1]]
            ])
            ->field("auto_id,source_code,order_code,order_date,order_list,number,row_id,warehouse_id,
shelves_id,(select name from fa_shelves s where s.id=t.shelves_id) shelves_name,shelves_type,quantity,u8userid,
cDepCode,cDepName,remark,createtime,(select order_code from fa_temporary where source_code=t.order_code and status in (0,1)) out_order,
(SELECT CONCAT(`name`,'_-_',number,'_-_',IFNULL(specification,''),'_-_',unit,'_-_',unit_code) inv_str FROM fa_inventory where number=t.number) inv_str")
            ->select();
            
            $new_temps = [];
            if($temps){
                foreach ($temps as $k=>$temp){
                    if(!$temp['out_order']){
                        unset($temp['out_order']);
                        $inv_arr = explode('_-_', $temp['inv_str']);
                        unset($temp['inv_str']);
                        $order_code = str_replace($pda_flag,'',$temp['order_code']);
                        
                        if(!isset($new_temps[$order_code])){
                            $new_temps[$order_code] = [
                                'auto_id' => $temp['auto_id'],
                                'source_code' => $temp['source_code'],
                                'FBillNo' => $order_code,
                                'order_type' => $pda_order_type,
                                'FDate' => $temp['order_date'],
                                'a_remark' => $temp['remark'],
                                'stock_id' => $temp['warehouse_id'],
                                'to_shelves_id' => $temp['shelves_id'],
                                'to_shelves_name' => $temp['shelves_name'],
                                'status' => 1,
                                'syn_status' => 1,
                                'total_qty' => 0,
                                'userid' => $temp['u8userid'],
                                'create_date' => substr($temp['createtime'],0,10)
                            ];
                        }
                        
                        $new_temps[$order_code]['total_qty'] += $temp['quantity'];
                        $new_temps[$order_code]['details'][] = [
                            'FBillNo' => $order_code,
                            'auto_id' => $temp['auto_id'],
                            'row_id' => $temp['row_id'],
                            'local_row_id' => $k+1,
                            'inv_number' => $inv_arr[1],
                            'inv_name' => $inv_arr[0],
                            'inv_specification' => $inv_arr[2],
                            'inv_attributes' => '',
                            'inv_unit' => $inv_arr[3],
                            'inv_unit_code' => $inv_arr[4],
                            'fqty' => $temp['quantity'],
                            'fauxqty' => 0,//拣货，已出库默认0
                            'shelves_id' => $temp['shelves_id'],
                            'shelves_name' => $temp['shelves_name'],
                            'shelves_type' => $temp['shelves_type'],
                            'b_remark' => ''
                        ];
                    }
                }
            }
            if(!$new_temps){
                exception('暂无单据');
            }
            $new_temps = array_values($new_temps);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        
        $this->success('ok',$new_temps);
    }
    
    /*
     * 同步pda日志
     *   */
    public function synActionLog(){
        $this->request->filter(['strip_tags']);
        $params = $this->request->param();
        if (!isset($params['data'])||!$params['data']){
            return;
        }

        Db::startTrans();
        try {
            $data = json_decode($params['data'],true);
            if($data){
                foreach ($data as $item){
                    $log = new Actionlog();
                    unset($item['id']);
                    $log->allowField(true)->save($item);
                }
                Db::commit();
            }
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }
    
    /*
     * 接受pda回传的出入库单数据
     * 接受pda回传的入库单箱头数据
     * $params 非空 ，为批量传
     *   */
    public function addStockBill($params = [],$backflag = false,$key = 0){
        $this->request->filter(['strip_tags']);
        if(!$params){
            $params = $this->request->param();
        }
        
        if(!$backflag){
            Db::startTrans();
        }
        
        try{
            if (!$params['bill']||!$params['billentry']){
                exception('单据为空，请核实');
            }
            
            $pdatype = intval($params['pdatype']);//pda单据类型
            $bill = json_decode($params['bill'],true);
            $billentry = json_decode($params['billentry'],true);
            $pda_flag = getPdaFlag($params['uuid']);//设备类型数组
            $online = isset($params['online'])?intval($params['online']):0;//默认离线版，1在线版
            
            if (!$bill||!$billentry){
                exception('单据[]为空，请核实');
            }
            
            //单个同步判断，批量同步的得另外加条件------------------------------
            $check = db('pda_bill')->where([
                'FBillNo' => $pda_flag.$bill['FBillNo'],
                'uuid' => $params['uuid']
            ])->find();
            
            if($check){
                //存在单号
                exception($check['FBillNo'].'单号已存在');
            }
            
            //不批量回传才判断  同时是离线版
            if(!$backflag&&!$online){
                $this->getPcBillStatus(true);//判断有无单据未处理
            }
            
            //处理单据新增pda单据
            //pdatype       0收货 1入库上架 2出库 3出库 4采购退货弃用 5领料退货弃用 11其他入库 12其他出库 13盘点 14采购退回15领料退回
            $autoPda = new Pda();
            //pda类型对应pc类型
            $pc_type_arr = $this->pc_type_arr;
            
            $pc_order_type = $pc_type_arr[$pdatype];
            $status = 0;//默认待处理
            if(config('site.order_type_'.$pc_order_type)){
                $status = 1;//已处理
            }
            
            db('pda_bill')->insert([
                'FBillNo' => $pda_flag.$bill['FBillNo'],
                'main' => $params['bill'],
                'detail' => $params['billentry'],
                'type' => $pdatype,//pda单据类型
                'pctype' => $pc_order_type,//pc单据类型
                'createtime' => time(),
                'status' => 1,//默认处理pda原始数据
                'uuid' =>$params['uuid'],
                'userid' => $params['userid'],
                'username' => $params['username']
            ]);
            
            $bill['userid'] = $params['userid'];
            $bill['username'] = $params['username'];
            if($pc_order_type==9){
                $bill['source_code'] = $bill['FBillNo'];// 记录pc单据号 只针对type=9盘点任务
            }
            
            //更新数组中，单号的值,增加pda标识
            $bill['FBillNo'] = $pda_flag.$bill['FBillNo'];//防止多只pda做单，单号冲突
            foreach ($billentry as &$item) {
                if (isset($item["FBillNo"])) {
                    $item["FBillNo"] = $pda_flag.$item["FBillNo"]; // 更新某列的值
                }
                
                //循环pda单据表体，在这里做初步判断，只有7,10，11的单据才能入代管仓，其他单据入代管仓的则提示
                if(config('site.shelves_wh_type_flag')){
                    if($pc_order_type==8){
                        Shelves::checkWhtypeById($item['shelves_id'],$item['to_shelves_id'], $pc_order_type);
                    }else{
                        Shelves::checkWhtypeById($item['shelves_id'],0, $pc_order_type);
                    }
                }
            }
            
            $autoPda->addPdaData($bill,$billentry,$pc_order_type,$status);
            
            //更新库存json
            //$this->getKcList('add');
            
            if(!$backflag){
                Db::commit();
            }
        }catch (\Exception $e){
            //跟踪日志，顺便打印出错误地方
            Log::error($bill['FBillNo'].'错误：'.$e->getMessage().PHP_EOL.$e->getTraceAsString());
            myApiLog('PDA回传单据',[
                '错误' => $e->getMessage(),
                '报错位置' => $e->getTraceAsString()
            ],$params);
            
            if(!$backflag){
                Db::rollback();
                $this->error($e->getMessage());
            }else{
                exception($e->getMessage());
            }
        }
        if(!$backflag){
            $this->success('ok');
        }
    }
    
    /*
     * 获取批量同步单据数据
     *   */
    public function addStockBills(){
        $this->request->filter(['strip_tags']);
        $params = $this->request->param();
        if (!$params['billentry']&&!$params['allots']&&!$params['checks']){
            $this->error('暂无可回传单据');
        }
        
        $stock_bills = json_decode($params['billentry'],true);
        $allot_bills = json_decode($params['allots'],true);
        $check_bills = json_decode($params['checks'],true);
        $online = isset($params['online'])?intval($params['online']):0;//默认离线版，1在线版
        
        Db::startTrans();
        try{
            if(!$online){
                //离线版才需要判断是否有待审核单据
                $this->getPcBillStatus(true);//判断有无单据未处理
            }
            
            if($stock_bills&&is_array($stock_bills)){
                $bills = [];
                $billentrys = [];
                //整理数据
                foreach ($stock_bills as $row){
                    //表头
                    if(!isset($bills[$row['FBillNo']])){
                        $bills[$row['FBillNo']] = [
                            "id" => $row['a_id'],
                            //"auto_id" => $row['auto_id'],//作废
                            "source_code" => $row['source_code'],
                            "order_type" => $row['order_type'],
                            "FBillNo" => $row['FBillNo'],
                            "FDate" => $row['FDate'],
                            "a_remark" => $row['a_remark'],
                            "stock_id" => $row['stock_id'],
                            "total_qty" => $row['total_qty'],
                            "factory_code" => $row['factory_code'],
                            "factory_name" => $row['factory_name'],
                            "userid" => $row['userid'],
                            "to_shelves_id" => isset($row['to_shelves_id'])?$row['to_shelves_id']:'',
                            "to_shelves_name" => isset($row['to_shelves_name'])?$row['to_shelves_name']:'',
                            "create_date" => $row['create_date']
                        ];
                    }
                    //表体
                    $billentrys[$row['FBillNo']][] = [
                        "id" => $row['b_id'],
                        "auto_id" => isset($row['auto_id'])?$row['auto_id']:0,
                        "row_id" => $row['row_id'],
                        "local_row_id" => $row['local_row_id'],
                        "inv_number" => $row['inv_number'],
                        "inv_name" => $row['inv_name'],
                        "inv_specification" => $row['inv_specification'],
                        "inv_attributes" => $row['inv_attributes'],
                        "inv_unit" => $row['inv_unit'],
                        "inv_unit_code" => $row['inv_unit_code'],
                        "fqty" => $row['fqty'],
                        "fauxqty" => $row['fauxqty'],
                        "cBatch" => isset($row['cBatch'])?$row['cBatch']:'',//批号
                        "shelves_id" => $row['shelves_id'],
                        "shelves_name" => $row['shelves_name'],
                        "shelves_type" => $row['shelves_type'],
                        "b_remark" => $row['b_remark']
                    ];
                }
                unset($params['billentry']);
                if($bills){
                    $key = 0;
                    foreach ($bills as $FBillNo=>$bill){
                        $params['pdatype'] = $bill['order_type'];
                        $params['bill'] = json_encode($bill);
                        $params['billentry'] = json_encode($billentrys[$FBillNo]);
                        $this->addStockBill($params,true,$key);//true 批量回传
                        $key++;
                    }
                }
            }
            
            //处理调拨
            if($allot_bills&&is_array($allot_bills)){
                $bills = [];
                $billentrys = [];
                //整理数据
                foreach ($allot_bills as $row){
                    //表头
                    if(!isset($bills[$row['FBillNo']])){
                        $bills[$row['FBillNo']] = [
                            "id" => $row['a_id'],
                            "FBillNo" => $row['FBillNo'],
                            "FDate" => $row['FDate'],
                            "type" => $row['type'],
                            "stock_id" => $row['stock_id'],
                            "to_stock_id" => $row['to_stock_id'],
                            "invStart" => $row['invStart'],
                            "invEnd" => $row['invEnd'],
                            "totalnum" => $row['totalnum'],
                            "userid" => $row['userid'],
                            "create_date" => $row['create_date'],
                            "remark" => $row['remark'],
                        ];
                    }
                    //表体
                    $billentrys[$row['FBillNo']][] = [
                        "id" => $row['b_id'],
                        "kc_id" => $row['kc_id'],
                        "inv_id" => $row['inv_id'],
                        "inv_number" => $row['inv_number'],
                        "inv_name" => $row['inv_name'],
                        "inv_specification" => $row['inv_specification'],
                        "inv_attributes" => $row['inv_attributes'],
                        "inv_unit" => $row['inv_unit'],
                        "inv_unit_code" => $row['inv_unit_code'],
                        "shelves_id" => $row['shelves_id'],
                        "to_shelves_id" => $row['to_shelves_id'],
                        "kc_qty" => $row['kc_qty'],
                        "cBatch" => $row['cBatch'],
                        "allot_qty" => $row['allot_qty']
                    ];
                }
                unset($params['allots']);
                if($bills){
                    $key = 0;
                    foreach ($bills as $FBillNo=>$bill){
                        $params['pdatype'] = 16;//调拨
                        $params['bill'] = json_encode($bill);
                        $params['billentry'] = json_encode($billentrys[$FBillNo]);
                        $this->addStockBill($params,true,$key);//true 批量回传
                        $key++;
                    }
                }
            }
            
            //处理盘点
            if($check_bills&&is_array($check_bills)){
                $bills = [];
                $billentrys = [];
                //整理数据
                foreach ($check_bills as $row){
                    //表头
                    if(!isset($bills[$row['FBillNo']])){
                        $bills[$row['FBillNo']] = [
                            "id" => $row['a_id'],
                            "FBillNo" => $row['FBillNo'],
                            "FDate" => $row['FDate'],
                            "bookDate" => $row['bookDate'],
                            "type" => $row['type'],
                            "stock_id" => $row['stock_id'],
                            "invStart" => $row['invStart'],
                            "invEnd" => $row['invEnd'],
                            "totalnum" => $row['totalnum'],
                            "userid" => $row['userid'],
                            "create_date" => $row['create_date'],
                            "remark" => $row['remark'],
                        ];
                    }
                    //表体
                    $billentrys[$row['FBillNo']][] = [
                        "id" => $row['b_id'],
                        "inv_number" => $row['inv_number'],
                        "inv_id" => $row['inv_id'],
                        "inv_name" => $row['inv_name'],
                        "inv_specification" => $row['inv_specification'],
                        "inv_attributes" => $row['inv_attributes'],
                        "inv_unit" => $row['inv_unit'],
                        "inv_unit_code" => $row['inv_unit_code'],
                        "shelves_id" => $row['shelves_id'],
                        "shelves_name" => $row['shelves_name'],
                        "kc_qty" => $row['kc_qty'],
                        "check_qty" => $row['check_qty'],
                        "isnew" => $row['isnew'],
                        "cBatch" => $row['cBatch'],
                        "scan_datetime" => $row['scan_datetime']
                    ];
                }
                unset($params['checks']);
                if($bills){
                    $key = 0;
                    foreach ($bills as $FBillNo=>$bill){
                        $params['pdatype'] = 13;//盘点
                        $params['bill'] = json_encode($bill);
                        $params['billentry'] = json_encode($billentrys[$FBillNo]);
                        $this->addStockBill($params,true,$key);//true 批量回传
                        $key++;
                    }
                }
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            //跟踪日志，顺便打印出错误地方
            Log::error('错误：'.$e->getMessage().PHP_EOL.$e->getTraceAsString());
            myApiLog('PDA批量回传单据',$e->getMessage(),$params,$e->getTraceAsString());
            
            $this->error($e->getMessage());
        }
        $this->success();
    }
    
    /*
     * 同步同时针对已回传但未变更状态的单据
     * 先判断单据，调拨、盘点暂不做同步判断
     *   */
    public function synPdaPcOrderStatus(){
        $this->request->filter(['strip_tags']);
        $params = $this->request->param();
        if (!$params['bills']&&!$params['allots']&&!$params['checks']){
            return ;
        }
        $stock_bills = json_decode($params['bills'],true);
        $allot_bills = json_decode($params['allots'],true);
        $check_bills = json_decode($params['checks'],true);
        
        $rebills = [
            'bills' => [],
            'allots' => [],
            'checks' => []
        ];
        
        $pda_flag = getPdaFlag($params['uuid']);//设备类型数组
        if($pda_flag){
            try{
                //单据
                if($stock_bills&&is_array($stock_bills)){
                    foreach ($stock_bills as $bill){
                        //状态同步判断
                        if(db('temporary')->where([
                            'order_code' => $pda_flag.$bill['FBillNo'],
                            'status' => ['IN',[0,1]]
                        ])->value('id')){
                            $rebills['bills'][] = $bill['id'];
                        }
                    }
                }
               
                //处理调拨
                if($allot_bills&&is_array($allot_bills)){
                    foreach ($allot_bills as $bill){
                        //状态同步判断
                        if(db('temporary')->where([
                            'order_code' => $pda_flag.$bill['FBillNo'],
                            'status' => ['IN',[0,1]]
                        ])->value('id')){
                            $rebills['allots'][] = $bill['id'];
                        }
                    }
                }
                
                //处理盘点
                if($check_bills&&is_array($check_bills)){
                    foreach ($check_bills as $bill){
                        //状态同步判断
                        if(db('temporary')->where([
                            'order_code' => $pda_flag.$bill['FBillNo'],
                            'status' => ['IN',[0,1]]
                        ])->value('id')){
                            $rebills['checks'][] = $bill['id'];
                        }
                    }
                }
            }catch (\Exception $e){
                //跟踪日志，顺便打印出错误地方
                myApiLog('同步同时针对已回传但未变更状态的单据',$e->getMessage(),$params,$e->getTraceAsString());
                $this->error($e->getMessage());
            }
            $this->success('ok',$rebills);
        }
    }

    /*
     * 获取wms平台配置的sql语句，直接更新pda，不用pda每次都去清空表结构
     *   */
    public function getPcSql(){
        $sql = config('site.pda_sql');//pda 要执行的sql
        if($sql){
            $sql_arr = explode(';', $sql);
            /*$new_sql_arr = array_filter($sql_arr,function($str){
                return str_replace("\r\n", "", $str);
            });*/
            return json($sql_arr);
        }
    }
}
